import 'package:flutter_riverpod/flutter_riverpod.dart';

/// 计数器状态类
/// 使用不可变类来管理状态
class CounterState {
  final int count;
  final String username;
  final bool isLoading;
  final String status;

  const CounterState({
    this.count = 0,
    this.username = 'Guest',
    this.isLoading = false,
    this.status = 'Zero',
  });

  /// 创建新状态的便捷方法
  CounterState copyWith({
    int? count,
    String? username,
    bool? isLoading,
    String? status,
  }) {
    return CounterState(
      count: count ?? this.count,
      username: username ?? this.username,
      isLoading: isLoading ?? this.isLoading,
      status: status ?? this.status,
    );
  }

  /// 根据计数器值计算状态
  String get counterStatus {
    if (count == 0) return 'Zero';
    if (count < 10) return 'Low';
    if (count < 50) return 'Medium';
    return 'High';
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is CounterState &&
        other.count == count &&
        other.username == username &&
        other.isLoading == isLoading &&
        other.status == status;
  }

  @override
  int get hashCode {
    return count.hashCode ^
        username.hashCode ^
        isLoading.hashCode ^
        status.hashCode;
  }

  @override
  String toString() {
    return 'CounterState(count: $count, username: $username, isLoading: $isLoading, status: $status)';
  }
}

/// 计数器状态管理器
/// 继承StateNotifier来管理状态变化
class CounterNotifier extends StateNotifier<CounterState> {
  CounterNotifier() : super(const CounterState());

  /// 增加计数器
  void increment() {
    final newCount = state.count + 1;
    state = state.copyWith(
      count: newCount,
      status: _getStatusForCount(newCount),
    );
  }

  /// 减少计数器
  void decrement() {
    if (state.count > 0) {
      final newCount = state.count - 1;
      state = state.copyWith(
        count: newCount,
        status: _getStatusForCount(newCount),
      );
    }
  }

  /// 重置计数器
  void reset() {
    state = state.copyWith(count: 0, status: 'Zero');
  }

  /// 设置用户名
  void setUsername(String username) {
    state = state.copyWith(username: username);
  }

  /// 批量增加
  void addMultiple(int value) {
    final newCount = state.count + value;
    state = state.copyWith(
      count: newCount,
      status: _getStatusForCount(newCount),
    );
  }

  /// 异步增加计数器
  Future<void> incrementAsync() async {
    // 设置加载状态
    state = state.copyWith(isLoading: true);

    // 模拟网络延迟
    await Future.delayed(const Duration(seconds: 2));

    // 更新计数器并清除加载状态
    final newCount = state.count + 1;
    state = state.copyWith(
      count: newCount,
      status: _getStatusForCount(newCount),
      isLoading: false,
    );
  }

  /// 设置到指定值
  void setCount(int value) {
    state = state.copyWith(count: value, status: _getStatusForCount(value));
  }

  /// 根据计数值获取状态
  String _getStatusForCount(int count) {
    if (count == 0) return 'Zero';
    if (count < 10) return 'Low';
    if (count < 50) return 'Medium';
    return 'High';
  }
}

/// 主要的计数器Provider
/// 使用StateNotifierProvider来管理状态
final counterProvider = StateNotifierProvider<CounterNotifier, CounterState>(
  (ref) => CounterNotifier(),
);

/// 只读的计数器值Provider
/// 演示如何创建派生状态
final counterValueProvider = Provider<int>((ref) {
  return ref.watch(counterProvider).count;
});

/// 只读的用户名Provider
final usernameProvider = Provider<String>((ref) {
  return ref.watch(counterProvider).username;
});

/// 只读的状态Provider
final statusProvider = Provider<String>((ref) {
  return ref.watch(counterProvider).status;
});

/// 只读的加载状态Provider
final isLoadingProvider = Provider<bool>((ref) {
  return ref.watch(counterProvider).isLoading;
});

/// 计算属性：是否为偶数
final isEvenProvider = Provider<bool>((ref) {
  final count = ref.watch(counterValueProvider);
  return count % 2 == 0;
});

/// 计算属性：距离下一个里程碑
final nextMilestoneProvider = Provider<String>((ref) {
  final count = ref.watch(counterValueProvider);
  final milestones = [10, 25, 50, 100, 250, 500, 1000];

  for (int milestone in milestones) {
    if (count < milestone) {
      return '距离 $milestone 还差 ${milestone - count}';
    }
  }
  return '您已达到所有里程碑！';
});

/// 计算属性：进度百分比（到100）
final progressTo100Provider = Provider<double>((ref) {
  final count = ref.watch(counterValueProvider);
  return (count / 100).clamp(0.0, 1.0);
});

/// 计算属性：进度百分比（到500）
final progressTo500Provider = Provider<double>((ref) {
  final count = ref.watch(counterValueProvider);
  return (count / 500).clamp(0.0, 1.0);
});

/// 计算属性：进度百分比（到1000）
final progressTo1000Provider = Provider<double>((ref) {
  final count = ref.watch(counterValueProvider);
  return (count / 1000).clamp(0.0, 1.0);
});

/// 设置管理器
/// 演示如何管理应用设置
class SettingsNotifier extends StateNotifier<Map<String, dynamic>> {
  SettingsNotifier()
    : super({'theme': 'light', 'notifications': true, 'autoSave': false});

  void updateSetting(String key, dynamic value) {
    state = {...state, key: value};
  }

  void resetSettings() {
    state = {'theme': 'light', 'notifications': true, 'autoSave': false};
  }
}

/// 设置Provider
final settingsProvider =
    StateNotifierProvider<SettingsNotifier, Map<String, dynamic>>(
      (ref) => SettingsNotifier(),
    );

/// 主题Provider
final themeProvider = Provider<String>((ref) {
  return ref.watch(settingsProvider)['theme'] ?? 'light';
});
